<template>
  <el-form>
    <el-form-item label="资源名称">
      <el-input v-model="resources.name"></el-input>
    </el-form-item>
    <el-form-item label="资源路径">
      <el-input v-model="resources.url"></el-input>
    </el-form-item>
    <el-form-item label="资源分类">
      <el-select v-model="resources.categoryId">
        <el-option
        v-for="item in categorys"
        :key="item.id"
        :label="item.name"
        :value="item.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="描述">
      <el-input type="textarea" v-model="resources.description"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onSubmit">确认</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getResourceCategory, getCreatedOrEdit, getEditResource } from '@/services/resource.js'

export default {
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    resId: {
      type: [Number, String]
    }
  },
  data () {
    return {
      resources: {},
      categorys: []
    }
  },
  created () {
    this.resourceCategory()
    if (this.isEdit) {
      this.editResource()
    }
  },
  methods: {
    // 取消按钮
    onCancel () {
      this.$emit('cancel')
      this.resources = {}
    },
    // 确定按钮
    async onSubmit () {
      const { data } = await getCreatedOrEdit(this.resources)
      if (data.code === '000000') {
        this.$message.success(this.isEdit ? '编辑成功' : '添加成功')
        this.resources = {}
        this.$emit('success')
      }
    },
    // 资源分类数据
    async resourceCategory () {
      const { data } = await getResourceCategory()
      console.log(data)
      if (data.code === '000000') {
        this.categorys = data.data
      }
    },
    // 编辑页面展示数据
    async editResource () {
      const { data } = await getEditResource(this.resId)
      this.resources = data.data
    }
  }
}
</script>

<style lang='scss' scoped></style>
